﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using Cngot.Extensions.EventBus.Kafka.Integration;

namespace Cngot.Extensions.Logger.Kafka
{
    [ProviderAlias("Kafka")]
    internal class KafkaLoggerProvider : ILoggerProvider
    {
        private readonly KafkaLoggerOptions loggerOptions;
        private readonly KafkaProducer producer;
        private readonly IServiceProvider _serviceProvider;
        public KafkaLoggerProvider(IServiceProvider serviceProvider, IOptionsMonitor<KafkaLoggerOptions> options)
        {
            _serviceProvider = serviceProvider;
            loggerOptions = options.CurrentValue;

            producer = KafkaProducer.Create(loggerOptions);
            producer.DefaultTopic = loggerOptions.Topic;
            producer.InitializeCount = loggerOptions.InitializeCount;
        }

        /// <summary>
        /// 创建Logger对象
        /// </summary>
        /// <param name="categoryName"></param>
        /// <returns></returns>
        public ILogger CreateLogger(string categoryName)
        {
            //可缓存实例，这里略过了
            return new KafkaLogger(_serviceProvider, categoryName, loggerOptions, producer);
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            producer.Dispose();
        }
    }
}
